package io.renren.handler;

import io.renren.builder.TextBuilder;
import io.renren.entity.Book;
import io.renren.entity.BookVideo;
import io.renren.entity.UserDefaultInfo;
import io.renren.entity.WxUser;
import io.renren.service.BookVideoService;
import io.renren.service.UserDefaultInfoService;
import io.renren.service.WxUserService;
import io.renren.utils.ConfigConstant;
import io.renren.utils.QrLogicUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: hongyuliu
 * @Date: 2020-09-09
 * @Version 1.0
 */
@Slf4j
@Component
public class VideoHandleUtils {
    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private BookVideoService bookVideoService;

    @Autowired
    private UserDefaultInfoService userDefaultInfoService;

    public WxMpXmlOutMessage getVideoListWxMpXmlOutMessage(WxMpXmlMessage wxMessage, WxMpService wxMpService,
                                                            String eventKey) {
        WxMpXmlOutNewsMessage.Item item1 = FengDiUtils.dealFengDi(eventKey);
        if (item1 != null) {
            WxMpXmlOutNewsMessage newsMessage = WxMpXmlOutMessage.NEWS()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .addArticle(item1)
                    .build();
            log.info("响应的图文消息为：" + newsMessage.toString());
            return newsMessage;
        }

        log.info("扫码用户：" + wxMessage.getFromUser() + ",二维码码值：" + eventKey);
        Map query = new HashMap();
        query.put("deleted", "0");
        query.put("qrcodeNo", eventKey);

        //获取视频信息
        List<BookVideo> bookVideoList = bookVideoService.queryList(query);
        if (bookVideoList == null || bookVideoList.size() == 0) {
            // String qrDesc = QrLogicUtil.getQrDesc(wxMessage.getEventKey());
            String qrDesc = QrLogicUtil.getQrDesc4YS(eventKey);
            // return new TextBuilder().build(qrDesc, wxMessage, wxMpService);
            if (StringUtils.isNotBlank(qrDesc)) {
                return new TextBuilder().build(qrDesc, wxMessage, wxMpService);
            } else {
                return null;
            }
        }

        List<WxMpXmlOutNewsMessage.Item> collect = bookVideoList.stream()
                .filter(bookVideo -> "0".equals(bookVideo.getBook().getDeleted()))
                .sorted(Comparator.comparing(BookVideo::getPageNo).thenComparing(BookVideo::getOrderField))
                .map(bookVideo -> {
                    WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
                    item.setDescription("立即点击查看内容");
                    item.setTitle(bookVideo.getVideoName());
                    item.setUrl(ConfigConstant.BASE_URL + "/api/video_detail.html?videoId=" + bookVideo.getId() + "&userFrom=1");
                    item.setPicUrl(StringUtils.isEmpty(bookVideo.getBook().getCoverUrl()) ? ConfigConstant.DEFAULT_BOOK_COVER : bookVideo.getBook().getCoverUrl());
                    return item;
                })
                .collect(Collectors.toList());
        if (collect == null || collect.size() <= 0) {
            return null;
        }
        WxMpXmlOutNewsMessage.Item[] items = new WxMpXmlOutNewsMessage.Item[collect.size()];
        WxMpXmlOutNewsMessage newsMessage = WxMpXmlOutMessage.NEWS()
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .addArticle(collect.toArray(items))
                .build();
        log.info("响应的图文消息为：" + newsMessage.toString());
        BookVideo video = bookVideoList.stream()
                .filter(bookVideo -> "0".equals(bookVideo.getBook().getDeleted()))
                .findFirst().orElse(null);
        if (video != null) {
            //获取用户信息,获取wxUser对象
            WxUser wxUser = new WxUser();
            Map userQuery = new HashMap();
            userQuery.put("openId", wxMessage.getFromUser());
            List<WxUser> wxUserList = wxUserService.queryList(userQuery);
            if (wxUserList != null && wxUserList.size() > 0) {
                wxUser = wxUserList.get(0);
            } else {
                try {
                    WxMpUser mpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
                    wxUser.setStatus("0");
                    wxUser.setSubscribe("1");
                    wxUser.setUnionId(mpUser.getUnionId());
                    wxUser.setOpenId(wxMessage.getFromUser());
                    wxUser.setImgUrl(mpUser.getHeadImgUrl());
                    wxUser.setNickName(mpUser.getNickname());
                    wxUserService.save(wxUser);
                } catch (WxErrorException e) {
                    e.printStackTrace();
                    return new TextBuilder().build("出现异常，请联系管理员处理", wxMessage, wxMpService);
                }
            }
            Book book = video.getBook();

            setDefaultInfo(book.getGradeId(), book.getSubjectId(), book.getVersionId(), wxUser.getId());
        }
        return newsMessage;
    }

    private void setDefaultInfo(Long gradeId, Long subjectId, Long versionId, Long userId) {
        Map query = new HashMap();
        query.put("userId", userId);
        query.put("gradeId", gradeId);
        query.put("subjectId", subjectId);
        List<UserDefaultInfo> userDefaultInfoList = userDefaultInfoService.queryList(query);
        UserDefaultInfo userDefaultInfo = new UserDefaultInfo();
        //如果没有则创建
        if (userDefaultInfoList == null || userDefaultInfoList.size() == 0) {
            userDefaultInfo.setUserId(userId);
            userDefaultInfo.setGradeId(gradeId);
            userDefaultInfo.setSubjectId(subjectId);
            userDefaultInfo.setVersionId(versionId);
            userDefaultInfo.setSeasonId(Long.parseLong(ConfigConstant.DEFAULT_SEASON_ID));
            userDefaultInfoService.save(userDefaultInfo);
        } else {
            //否则更新
            userDefaultInfo = userDefaultInfoList.get(0);
            userDefaultInfo.setGradeId(gradeId);
            userDefaultInfo.setSubjectId(subjectId);
            userDefaultInfo.setVersionId(versionId);
            userDefaultInfo.setUpdateTime(new Date());
            userDefaultInfoService.update(userDefaultInfo);
        }
    }
}
